package nl.hanze.designpatterns.DAO.impl.db;

import nl.hanze.designpatterns.DAO.TroubleTicketDAO;
import nl.hanze.designpatterns.Domain.LoginCredential;
import nl.hanze.designpatterns.Domain.TroubleTicket;
import nl.hanze.designpatterns.db.Executor;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 *
 * Created by Aron on 25-9-2014.
 */
public class TroubleTicketDAOImpl extends BaseDAOImpl implements TroubleTicketDAO {
    @Override
    public List<TroubleTicket> getTroubleTickets() {
        List<TroubleTicket> list = new ArrayList<>();
        Iterator<TroubleTicket> iterator = null;
        try {
            iterator = executor.getIterator(TroubleTicket.class, "SELECT * FROM TroubleTicket");
        } catch (SQLException e) {
            e.printStackTrace();
        }
        if (iterator == null) {
            return list;
        }
        while (iterator.hasNext()){
            TroubleTicket ticket = iterator.next();
            list.add(ticket);
        }
        return list;
    }

    @Override
    public List<TroubleTicket> getTroubleTicketsByName(String callerName) {
        List<TroubleTicket> list = new ArrayList<>();
        for (TroubleTicket ticket : getTroubleTickets() ) {
            if (ticket.getCallerName().equals(callerName)) {
                list.add(ticket);
            }
        }
        return list;
    }

    @Override
    public void saveTroubleTicket(TroubleTicket troubleticket) {
        String query;
        if (troubleticket.getId() > 0) {

            String queryTemplate = "UPDATE `troubleticket` SET `description` = '%s' WHERE `id` = %d;";
            query = String.format(queryTemplate,
                    troubleticket.getDescription(),
                    troubleticket.getId());
        } else {
            String queryTemplate = "INSERT INTO `TroubleTicket` (`userName`, `callerName`, `description`, `dateTime`) " +
                    "VALUES ('%s', '%s', '%s', '%s');";
            query = String.format(queryTemplate,
                    troubleticket.getUserName(),
                    troubleticket.getCallerName(),
                    troubleticket.getDescription(),
                    troubleticket.getDateTime());
        }
        System.out.println("[QUERY] "+ query);
        try {
            Executor.executeChange(query);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
